package com.jdew.thkj.fragment;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.jdew.thkj.R;
import com.jdew.thkj.activity.LoginActivity;
import com.jdew.thkj.activity.MainActivity;
import com.jdew.thkj.activity.TbProductDetailActivity;
import com.jdew.thkj.base.BaseFragment;
import com.jdew.thkj.dialog.CommonDialog;
import com.jdew.thkj.manager.AppConfig;
import com.jdew.thkj.network.RetrofitManager;
import com.jdew.thkj.network.api.RequestApi;
import com.jdew.thkj.utils.MD5Utils;
import com.jdew.thkj.utils.RegexValidateUtils;
import com.jdew.thkj.utils.ToastUtils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.Bind;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by yangzai on 2018/1/23 0023.
 */

public class LinkFragment extends BaseFragment implements View.OnClickListener {
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.link)
    EditText link;
    @Bind(R.id.one_search)
    Button oneSearch;
    @Bind(R.id.fastpaste)
    TextView fastpaste;
    private String tkl;
    private String ItemId = null;
    private MainActivity activity;
    private String e;

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_link;
    }

    @Override
    protected void onCreateViewT() {
        activity = (MainActivity) getActivity();
        fastpaste.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
        fastpaste.setOnClickListener(this);
        oneSearch.setOnClickListener(this);
        title.setText("转链");
    }

    @Override
    public void initData() {
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fastpaste: {
                pasteToResult();
            }
            break;
            case R.id.one_search: {
                if (sp.getString("SpareTwo", "").equals("")) {
                    startActivity(new Intent(activity, LoginActivity.class));
                    return;
                }
                if (sp.getString("UserSjPhone", "").equals("") && (sp.getString("SpareTwo", "").equals("0") || sp.getString("SpareTwo", "").equals("2"))) {
                    activity.toset("检测到您还没有绑定上级,请到我的页面绑定上级");
                    return;
                }
                if (!RegexValidateUtils.isFastClick()) {
                    return;
                }
                String result = link.getText().toString();
                String str = RegexValidateUtils.removeNonBmpUnicode(result).replace("#", "");
                if (str.contains("￥") || str.contains("€") || str.contains("《")) {
                    if (str.contains("这段描述")) {
                        tkl = str.substring(str.indexOf("这段描述"));
                    } else if (str.contains("拷贝")) {
                        tkl = str.substring(str.indexOf("拷贝"));
                    } else {
                        tkl = str;
                    }
                } else {
                    tkl = str;
                }
                if (TextUtils.isEmpty(link.getText())) {
                    ToastUtils.getInstance(activity).showMessage("链接或淘口令不能为空!");
                } else if (!(((str.contains("https:") || str.contains("http:"))) && str.contains("&id=") || str.contains("/i") || str.contains("?id=") || str.contains("itemId=") || str.contains("?e="))) {
                    parseTkl();
                } else if ((str.contains("https:") || str.contains("http:"))) {
                    try {
                        if (str.contains("?e=")) {
                            e = str.substring(str.indexOf("?e=") + 3);
                            getItemId(e);
                            return;
                        } else if (str.contains("&id=") || str.contains("/i") || str.contains("?id=") || str.contains("itemId=")) {
                            ItemId = getHttpItemId(str);
                        } else {
                            ToastUtils.getInstance(activity).showMessage("请输入正确的链接或淘口令!");
                            return;
                        }
                    } catch (Exception e) {
                        ToastUtils.getInstance(activity).showMessage("该商品暂无佣金计划或已下架!");
                        return;
                    }

                    if (sp.getString("userPhone", "").equals("")) {
                        startActivity(new Intent(activity, LoginActivity.class));
                        return;
                    } else if (sp.getString("UserSjPhone", "").equals("") && (sp.getString("SpareTwo", "").equals("0") || sp.getString("SpareTwo", "").equals("2"))) {
                        activity.toset("检测到您还没有绑定上级,请到我的页面绑定上级");
                    } else {
                        toDetail();
                    }
                } else if (TextUtils.isEmpty(link.getText())) {
                    ToastUtils.getInstance(activity).showMessage("链接或淘口令不能为空!");
                } else {
                    ToastUtils.getInstance(activity).showMessage("此淘口令无法解析!");
                }
                break;
            }
            default:
                break;
        }
    }

    public void toset(String message) {
        new CommonDialog.Builder(activity)
                .setTitle("提示")
                .setMessage(message)
                .setdialogPostive("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                    }
                }).show();
    }

    public void parseTkl() {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).GetTkl(tkl, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "tkl" + tkl)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(JSONObject obj) {
                if (null != obj && obj.get("code").equals("0")) {
                    ItemId = getHttpItemId(obj.getString("data"));
                } else {
                    ToastUtils.getInstance(activity).showMessage("此淘口令无法解析!");
                }
                if (sp.getString("userPhone", "").equals("")) {
                    startActivity(new Intent(activity, LoginActivity.class));
                    return;
                } else if (sp.getString("UserSjPhone", "").equals("") && (sp.getString("SpareTwo", "").equals("0") || sp.getString("SpareTwo", "").equals("2"))) {
                    toset("检测到您还没有绑定上级,请到我的页面绑定上级");
                } else if (null == ItemId) {
                    ToastUtils.getInstance(activity).showMessage("此淘口令无法解析!");
                } else if (ItemId.contains("?e=")) {
                    e = ItemId.substring(ItemId.indexOf("?e=") + 3);
                    getItemId(e);
                } else if (ItemId.contains("&e=")) {
                    e = ItemId.substring(ItemId.indexOf("&e=") + 3);
                    getItemId(e);
                } else {
                    toDetail();
                }
            }
        });
    }

    private void pasteToResult() {
        ClipboardManager cm = (ClipboardManager) activity.getApplicationContext().getSystemService(activity.CLIPBOARD_SERVICE);
        String resultString = "";
        // 检查剪贴板是否有内容
        if (!cm.hasPrimaryClip()) {
        } else {
            ClipData clipData = cm.getPrimaryClip();
            int count = clipData.getItemCount();
            for (int i = 0; i < count; ++i) {
                ClipData.Item item = clipData.getItemAt(i);
                CharSequence str = item.coerceToText(activity);
                resultString += str;
            }

        }
        link.setText(resultString);
        link.setSelection(link.getText().length());
        cm.setPrimaryClip(ClipData.newPlainText(null, ""));
    }

    public void toDetail() {
        Bundle b = new Bundle();
        if (null != ItemId) {
            b.putSerializable("itemId", ItemId);
            startActivity(TbProductDetailActivity.class, b);
        } else {
            ToastUtils.getInstance(activity).showMessage("请输入正确的链接或淘口令!");
        }
    }

    private String getHttpItemId(String str) {
        Pattern p = Pattern.compile("\\d+");

        if (null == str) {
            return null;
        } else if (str.contains("&id=")) {
            Matcher m = p.matcher(str.substring(str.lastIndexOf("&id=")).substring(4));
            if (m.find()) {
                return m.group();
            }
        } else if (str.contains("?id=")) {
            Matcher m = p.matcher(str.substring(str.lastIndexOf("?id=")).substring(4));
            if (m.find()) {
                return m.group();
            }
        } else if (str.contains("itemId=")) {
            Matcher m = p.matcher(str.substring(str.lastIndexOf("itemId=")).substring(7));
            if (m.find()) {
                return m.group();
            }
        } else if (str.contains("?e=")) {
            return str;
        } else if (str.contains("&e=")) {
            return str;
        } else if (str.contains("/i")) {
            Matcher m = p.matcher(str.substring(str.lastIndexOf("/i")).substring(2));
            if (m.find()) {
                return m.group();
            }
        } else {
            return null;
        }
        return null;
    }

    @Override
    public void onResume() {
        super.onResume();
        sp = activity.getSharedPreferences("user", Activity.MODE_PRIVATE);
        editor = sp.edit();
        ItemId = null;
        pasteToResult();
    }

    public void getItemId(String e) {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).GetTBItemId(e, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "e" + e)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(JSONObject obj) {
                if (obj.getString("code").equals("0")) {
                    ItemId = obj.getString("data");
                    toDetail();
                }
            }
        });
    }
}
